package com.example.memorypoint.mvp.aichat;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.memorypoint.API.GeminiClient;
import com.example.memorypoint.DateBase.DiaryDatabase;
import com.example.memorypoint.entity.Msg;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AiChatPresenterImpl implements AiChatContract.AiChatPresenter {

    private AiChatContract.AiChatView view;
    private DiaryDatabase diaryDatabase;
    private String latestDiary;
    private ExecutorService executor;
    private Handler mainHandler;

    public AiChatPresenterImpl(AiChatContract.AiChatView view, DiaryDatabase diaryDatabase) {
        this.view = view;
        this.diaryDatabase = diaryDatabase;
        this.executor = Executors.newSingleThreadExecutor();
        this.mainHandler = new Handler(Looper.getMainLooper());
        // 从数据库中获取最新日记内容
        latestDiary = diaryDatabase.getContentById(diaryDatabase.getLatestDiaryId());
    }

    @Override
    public void initChat() {
        // 添加初始欢迎消息
        view.addMessage(new Msg("你好，我是你的心灵小助手，有什么事情都可以分享给我哦，我会尽可能给予你帮助的。", Msg.TYPE_RECEIVED));
    }

    @Override
    public void sendMessage(String message) {
        // 用户发送消息：先添加用户消息
        view.addMessage(new Msg(message, Msg.TYPE_SEND));
        // 获取当前消息列表大小（这将作为加载中消息的位置）
        int loadingIndex = view.getMessageListSize();
        // 添加加载中提示消息
        view.addMessage(new Msg("正在思考...", Msg.TYPE_RECEIVED));

        executor.execute(() -> {
            try {
                String prompt = "请一直记住从开始对话起，你就是一个心灵小助手，请注意说话语气要照顾我的心情,下面是我最新的日记，请你根据日记内容判断出写日记者的人的心情来调整你说话的语气" + latestDiary;
                String response = GeminiClient.getResponseWithOkHttpAndFastJson(prompt, message);
                // 在主线程更新加载中的消息
                mainHandler.post(() -> {
                    view.updateMessageAt(loadingIndex, new Msg(response, Msg.TYPE_RECEIVED));
                });
            } catch (IOException e) {
                e.printStackTrace();
                mainHandler.post(() -> {
                    Log.e("AiChatPresenter", "Request failed: " + e.getMessage());
                    view.updateMessageAt(loadingIndex, new Msg("网络异常，请稍后重试。", Msg.TYPE_RECEIVED));
                });
            }
        });
    }

    @Override
    public void detachView() {
        view = null;
    }
}
